﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MyCalculator
{
    public partial class StandardCalculator : UserControl    //标准计算器
    {
        protected double? firstNumber = null;
        protected string currentNumber = "0";       //当前显示的数字
        protected char? pendingOperation = null;
        protected bool newNumber = true;

        public StandardCalculator()
        {
            InitializeComponent();          //初始化控件
            InitializeEvents();         //初始化事件
        }

        protected void InitializeEvents()
        {
            // 数字按钮事件
            btn0.Click += NumberClick;
            btn1.Click += NumberClick;
            btn2.Click += NumberClick;
            btn3.Click += NumberClick;
            btn4.Click += NumberClick;
            btn5.Click += NumberClick;
            btn6.Click += NumberClick;
            btn7.Click += NumberClick;
            btn8.Click += NumberClick;
            btn9.Click += NumberClick;

            // 操作按钮
            btnAdd.Click += OperationClick;
            btnSubtract.Click += OperationClick;
            btnMultiply.Click += OperationClick;
            btnDivide.Click += OperationClick;

            // 功能按钮
            btnCE.Click += (s, e) => ClearEntry();
            btnC.Click += (s, e) => ClearAll();
            btnBackspace.Click += BackspaceClick;
            btnDecimal.Click += DecimalClick;
            btnSign.Click += SignClick;
            btnEquals.Click += EqualsClick;
        }

        protected void UpdateDisplay()
        {
            txtResult.Text = currentNumber;
            if (txtResult.Text.Length > 12)
                txtResult.Font = new Font("Segoe UI", 20F);
            else
                txtResult.Font = new Font("Segoe UI", 24F);
        }

        //按下数字键
        protected void NumberClick(object sender, EventArgs e)
        {
            var button = (Button)sender;
            if (newNumber)
            {
                currentNumber = "0";
                newNumber = false;
            }

            if (currentNumber == "0")
                currentNumber = button.Text;
            else
                currentNumber += button.Text;

            UpdateDisplay();
        }

        //按下符号键
        protected void OperationClick(object sender, EventArgs e)
        {
            var button = (Button)sender;
            if (double.TryParse(currentNumber, out double number))
            {
                if (firstNumber == null)
                {
                    firstNumber = number;
                    pendingOperation = button.Text[0];
                    txtExpression.Text = $"{firstNumber} {pendingOperation} ";
                    newNumber = true;
                }
                else
                {
                    // 显示完整表达式 "3 + 5 + " 而不是 "8 + "
                    txtExpression.Text = $"{firstNumber} {pendingOperation} {number} ";
                    Calculate();
                    pendingOperation = button.Text[0];
                    txtExpression.Text = $"{currentNumber} {pendingOperation} ";
                }
            }
        }

        //按下等号键
        protected void EqualsClick(object sender, EventArgs e)
        {
            if (firstNumber != null && pendingOperation != null)
            {
                // 先保存当前输入作为第二个操作数
                string secondNumber = currentNumber;

                // 更新表达式显示
                txtExpression.Text = $"{firstNumber} {pendingOperation} {secondNumber} = ";

                // 执行计算
                Calculate();

                // 在表达式末尾追加结果
                txtExpression.Text += currentNumber;

                firstNumber = null;
                pendingOperation = null;
            }
        }

        //进行运算操作
        protected virtual void Calculate()
        {
            if (double.TryParse(currentNumber, out double secondNumber))
            {
                try
                {
                    switch (pendingOperation)
                    {
                        case '+':
                            firstNumber += secondNumber;
                            break;
                        case '-':
                            firstNumber -= secondNumber;
                            break;
                        case '×':
                            firstNumber *= secondNumber;
                            break;
                        case '÷':
                            if (secondNumber == 0)
                                throw new DivideByZeroException();    //除0异常处理
                            firstNumber /= secondNumber;
                            break;
                    }
                    currentNumber = firstNumber?.ToString("G15").TrimEnd('0').TrimEnd('.') ?? "0";
                    UpdateDisplay();
                    newNumber = true;
                }
                catch (DivideByZeroException)
                {
                    ClearAll();
                    txtResult.Text = "不能除以零";
                }
            }
        }

        //C
        protected void ClearAll()
        {
            firstNumber = null;
            pendingOperation = null;
            currentNumber = "0";
            txtExpression.Text = "";
            UpdateDisplay();
        }

        //CE
        protected void ClearEntry()
        {
            currentNumber = "0";
            UpdateDisplay();
        }

        //撤销一位操作
        protected void BackspaceClick(object sender, EventArgs e)
        {
            if (currentNumber.Length > 0)
            {
                currentNumber = currentNumber.Substring(0, currentNumber.Length - 1);
                if (currentNumber == "") currentNumber = "0";
                UpdateDisplay();
            }
        }

        //加入一位小数点
        protected void DecimalClick(object sender, EventArgs e)
        {
            if (!currentNumber.Contains("."))
            {
                currentNumber += ".";
                UpdateDisplay();
            }
        }

        //取相反数
        protected void SignClick(object sender, EventArgs e)
        {
            if (currentNumber != "0")
            {
                if (currentNumber.StartsWith("-"))
                    currentNumber = currentNumber.Substring(1);
                else
                    currentNumber = "-" + currentNumber;
                UpdateDisplay();
            }
        }

        //兼容科学计算器派生类功能
        protected virtual void SetupScientificUI()
        {
           
        }

        protected void UpdateExpression(string operation)
        {
            txtExpression.Text = operation;
        }

        protected void ResetState()
        {
            firstNumber = null;
            pendingOperation = null;
            newNumber = true;
        }
    }
}